package com.example.terminal.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.terminal.R;
import com.example.terminal.adapter.StoreListDetailsAdapter;
import com.example.terminal.adapter.StoreScanAdapter;
import com.example.terminal.base.BaseActivity;
import com.example.terminal.bean.CommonBean;
import com.example.terminal.bean.StoreListDetailsBean;
import com.example.terminal.bean.StoreListDetailsBean.DataBean;
import com.example.terminal.bean.StoreListDetailsBean.DataBean.TstoregeInDeviceBean;
import com.example.terminal.bean.StoreListDetailsBean.DataBean.TstoregeInDeviceBean.tstoregeInDeviceDetailListBean;
import com.example.terminal.global.Constant;
import com.example.terminal.http.NetworkUtils;
import com.example.terminal.http.network.OkGoBackListener;
import com.example.terminal.listener.OnItemClickListener;
import com.example.terminal.listener.OnTextClickListener;
import com.example.terminal.util.CommonUtils;
import com.example.terminal.util.DensityUtils;
import com.example.terminal.util.ToastUtils;
import com.example.terminal.view.CustomCircleProgress;
import com.example.terminal.view.CustomProgress;
import com.example.terminal.view.edit.EditorActivity;
import com.example.terminal.view.zxing.QRActivity;
import com.google.zxing.ResultPoint;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.CompoundBarcodeView;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.io.Serializable;
import java.util.List;

/**
 * 入库办理--扫描页面
 */
public class StoreScanActivity extends BaseActivity {
    private TwinklingRefreshLayout mRefreshLayout;
    private RecyclerView mRvContainer;
    private RelativeLayout mRlContentNull;
    private ImageButton mIbBack;
    private TextView mTv_Column, mTv_Model, mTv_Supplier, mTvTitleName, mTv_Variable, mTv_Operate, mTv_Save, mTv_SerialNumber;
    private EditText mEt_Input;
    private LinearLayout mLl_Input;
    private CustomProgress mIv_progress;
    private StoreScanAdapter storeScanAdapter;
    private CompoundBarcodeView barcodeView;
    private List<tstoregeInDeviceDetailListBean> tstoregeInDeviceDetailList;
    private int mPosition;
    private String mStatus;
    private String mImeiStatus;
    private MediaPlayer player;
    private final long pauseDuration = 1000; // 停顿时间，单位毫秒
    private StoreListDetailsBean mStoreListDetailsBean;
    private DataBean dataBean;
    private TstoregeInDeviceBean tstoregeInDeviceBean;

    @Override
    protected int setContentView() {
        return R.layout.activity_store_scan;
    }

    @Override
    protected void initView() {
        barcodeView = findViewById(R.id.barcodeView);//扫描窗口

        mRefreshLayout = findViewById(R.id.mRefreshLayout);
        mRvContainer = findViewById(R.id.mRvContainer);
        mRlContentNull = findViewById(R.id.mRlContentNull);

        mTv_Column = findViewById(R.id.mTv_Column);//数量
        mTv_Model = findViewById(R.id.mTv_Model);//型号
        mTv_Supplier = findViewById(R.id.mTv_Supplier);//供应商
        mIv_progress = findViewById(R.id.mIv_progress);//进度条

        mTvTitleName = findViewById(R.id.mTvTitleName);//标题
        mIbBack = findViewById(R.id.mIbBack);//返回

        mTv_Variable = findViewById(R.id.mTv_Variable);//序列号/数量
        mTv_Operate = findViewById(R.id.mTv_Operate);//操作
        mTv_Save = findViewById(R.id.mTv_Save);//保存按钮
        mTv_SerialNumber = findViewById(R.id.mTv_SerialNumber);//序号
        mEt_Input = findViewById(R.id.mEt_Input);//输入框
        mLl_Input = findViewById(R.id.mLl_Input);

        mIbBack.setOnClickListener(this::onClickSort);
        mTv_Save.setOnClickListener(this::onClickSort);

        //判断权限
        isPermissions();


        mEt_Input.addTextChangedListener(new TextWatcher() {
            // 输入前调用
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // s：变化前的文本
                // start：变化开始的位置
                // count：被替换的字符数
                // after：新输入的字符数
            }

            // 输入中调用（实时监听）
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // s：变化后的文本
                // start：变化开始的位置
                // before：被替换的字符数
                // count：新输入的字符数

                // 示例：实时获取输入内容
                int input = CommonUtils.stringToint(s.toString());
                mIv_progress.setCurrentValue(input);
            }

            // 输入完成（文本变化后）调用
            @Override
            public void afterTextChanged(Editable s) {
                // s：最终的文本（可修改）
                // 示例：输入完成后处理
                int result = CommonUtils.stringToint(s.toString());
                mIv_progress.setCurrentValue(result);
            }
        });
    }

    @Override
    protected void initData() {
        mPosition = mBundle.getInt(Constant.TurnType);
        mStoreListDetailsBean = (StoreListDetailsBean) mBundle.getSerializable(Constant.INFO);

        if (mStoreListDetailsBean != null) {
            dataBean = mStoreListDetailsBean.getData();
            if (dataBean != null) {
                tstoregeInDeviceBean = dataBean.getTstoregeInDevice().get(mPosition);
                mStatus = dataBean.getStatus();
                if (tstoregeInDeviceBean != null) {
                    tstoregeInDeviceDetailList = tstoregeInDeviceBean.getTstoregeInDeviceDetailList();
                }
            }
        }

        if (tstoregeInDeviceBean != null) {
            mImeiStatus = tstoregeInDeviceBean.getImeiStatus();
        }

        //判断是否扫描添加还是手动添加 1扫描
        if (mImeiStatus.equals("1")) {
            barcodeView.setVisibility(View.VISIBLE);
            mTv_Variable.setText("序列号");
        } else {
            mLl_Input.setVisibility(View.VISIBLE);
            mTv_Variable.setText("数量");
        }

        if (tstoregeInDeviceBean != null) {
            mTvTitleName.setText(tstoregeInDeviceBean.getDeviceName());
            mTv_Model.setText(tstoregeInDeviceBean.getDeviceType());
            mTv_Supplier.setText(tstoregeInDeviceBean.getDeviceCompany());

            mIv_progress.setMaxValue(tstoregeInDeviceBean.getDeviceNum());
            mTv_Column.setText(String.valueOf(tstoregeInDeviceBean.getDeviceNum()));
        }

    }

    @Override
    protected void initConnect() {

        if (!mImeiStatus.equals("1") && tstoregeInDeviceDetailList.size() == 0) {
            TstoregeInDeviceBean.tstoregeInDeviceDetailListBean tstoregeInDeviceDetailListBean = new TstoregeInDeviceBean.tstoregeInDeviceDetailListBean();
            tstoregeInDeviceDetailListBean.setCreateName(dataBean.getCreateName());
            tstoregeInDeviceDetailListBean.setCreateTime(CommonUtils.getTime());
            tstoregeInDeviceDetailListBean.setNum(0);
            tstoregeInDeviceDetailList.add(tstoregeInDeviceDetailListBean);
        } else if (!mImeiStatus.equals("1") && tstoregeInDeviceDetailList.size() == 1) {
            mEt_Input.setText(String.valueOf(tstoregeInDeviceDetailList.get(0).getNum()));
        }

        if (mImeiStatus.equals("1")) {
            initAdapter();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        barcodeView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        barcodeView.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*
         * 释放 音乐资源    防止内存泄漏
         * */
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Constant.REQUEST_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被授予，执行相应操作
                    barcodeView.decodeContinuous(callback);
                } else {
                    // 权限被拒绝，执行相应操作
                    ToastUtils.showToast("用户拒绝访问相机权限");
                }
            }
        }
    }

    /**
     *
     */

    public void onClickSort(View view) {
        switch (view.getId()) {
            case R.id.mIbBack:
                onFinish();
                break;
            case R.id.mTv_Save:
                int deviceNum = tstoregeInDeviceBean.getDeviceNum();

                mBundle = new Bundle();

                if (mImeiStatus.equals("1")) {
//                    if (deviceNum != tstoregeInDeviceDetailList.size()) {
//                        if (deviceNum > 0) {
//                            int num = deviceNum - tstoregeInDeviceDetailList.size();
//                            ToastUtils.showToast("明细还差" + num + "条");
//                        }
//                        return;
//                    }

                    mBundle.putInt(Constant.Volume, tstoregeInDeviceDetailList.size());
                } else {
                    if (mEt_Input == null)
                        return;

                    int toint = CommonUtils.stringToint(mEt_Input.getText().toString());

                    if (deviceNum < toint) {
                        ToastUtils.showToast("设备数量不能大于总数量!");
                        return;
                    }

                    tstoregeInDeviceDetailList.get(0).setNum(toint);

                    mBundle.putInt(Constant.Volume, toint);
                }
                mBundle.putInt(Constant.POSITION, mPosition);
                mBundle.putSerializable(Constant.INFO, (Serializable) tstoregeInDeviceDetailList);
                onFinish(mBundle, 550);
                break;
        }
    }

    private void initAdapter() {
        if (mStoreListDetailsBean == null)
            return;

//        if (tstoregeInDeviceDetailList.size() == 0 || tstoregeInDeviceDetailList.get(tstoregeInDeviceDetailList.size() - 1) != null) {
//            if (!mImeiStatus.equals("1") && tstoregeInDeviceDetailList.size() == 0) {
//                tstoregeInDeviceDetailList.add(null);
//            }
//        }

        mRlContentNull.setVisibility(tstoregeInDeviceDetailList == null || tstoregeInDeviceDetailList.size() == 0 ? View.VISIBLE : View.GONE);
        mRefreshLayout.setVisibility(tstoregeInDeviceDetailList == null || tstoregeInDeviceDetailList.size() == 0 ? View.GONE : View.VISIBLE);


        if (storeScanAdapter == null) {
            storeScanAdapter = new StoreScanAdapter(mActivity, tstoregeInDeviceDetailList, mImeiStatus, mStatus);
            mRvContainer.setAdapter(storeScanAdapter);
            mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

            storeScanAdapter.setOnTextClickListener(mItemTextClickListener);
            storeScanAdapter.setOnItemClickListener(new ItemClickListener());
        } else {
            storeScanAdapter.updateAdapter(tstoregeInDeviceDetailList);
        }
    }

    private class ItemClickListener extends OnItemClickListener {
        @Override
        public void onClick(View view, int position) {
            // 新增
//            if (tstoregeInDeviceDetailList.size()+1==dataBean.)
            tstoregeInDeviceDetailList.remove(null);
            if (!mImeiStatus.equals("1")) {
                if (tstoregeInDeviceDetailList.size() == 0) {
                    tstoregeInDeviceDetailList.add(null);
                    tstoregeInDeviceDetailList.add(tstoregeInDeviceDetailList.size() - 1, new TstoregeInDeviceBean.tstoregeInDeviceDetailListBean());
                }
            } else {
                if (tstoregeInDeviceDetailList.size() != 5) {
                    tstoregeInDeviceDetailList.add(null);
                    tstoregeInDeviceDetailList.add(tstoregeInDeviceDetailList.size() - 1, new TstoregeInDeviceBean.tstoregeInDeviceDetailListBean());
                }
            }
            initAdapter();
        }
    }


    private OnTextClickListener mItemTextClickListener = new OnTextClickListener() {

        @Override
        public void onClick(View view, int position) {
            switch (view.getId()) {
                case R.id.mIv_delete:
                    if (!mImeiStatus.equals("1") && tstoregeInDeviceDetailList.size() == 1) {
                        ToastUtils.showToast("最后数据不可删除!");
                        return;
                    }

                    if (position >= 0 && position < tstoregeInDeviceDetailList.size()) {
                        tstoregeInDeviceDetailList.remove(position);
                        initAdapter();
                    }
                    mIv_progress.setCurrentValue(tstoregeInDeviceDetailList.size());
                    break;
            }
        }
    };

    private void isPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQUEST_CODE);
        } else {
            // 如果有权限，直接启动扫描
            barcodeView.decodeContinuous(callback);
        }
    }

    private BarcodeCallback callback = new BarcodeCallback() {

        @Override
        public void barcodeResult(BarcodeResult result) {
            if (result != null && dataBean != null) {

                if (tstoregeInDeviceBean.getDeviceNum() != tstoregeInDeviceDetailList.size()) {

                    //扫描内容
                    String content = result.getText().toString();

                    if (content == null || content.equals("")) {
                        ToastUtils.showToast("序列号不能为空!");
                        return;
                    }

                    String createName = dataBean.getCreateName();

                    if (tstoregeInDeviceDetailList != null && tstoregeInDeviceDetailList.size() == 0) {
                        TstoregeInDeviceBean.tstoregeInDeviceDetailListBean tstoregeInDeviceDetailListBean = new TstoregeInDeviceBean.tstoregeInDeviceDetailListBean();
                        tstoregeInDeviceDetailListBean.setCreateName(createName);
                        tstoregeInDeviceDetailListBean.setCreateTime(CommonUtils.getTime());
                        tstoregeInDeviceDetailListBean.setImei(content);
                        tstoregeInDeviceDetailList.add(tstoregeInDeviceDetailListBean);

                        mIv_progress.setCurrentValue(tstoregeInDeviceDetailList.size());

                        openMusic(true);
                    } else {
                        boolean hasDuplicate = false;
                        for (int i = 0; i < tstoregeInDeviceDetailList.size(); i++) {
                            if (content.equals(tstoregeInDeviceDetailList.get(i).getImei())) {
                                hasDuplicate = true;
                                openMusic(false);
                                break;
                            }
                        }
                        if (hasDuplicate) {
                            ToastUtils.showToast("不能重复添加一样的序列号!");
                        } else {
                            TstoregeInDeviceBean.tstoregeInDeviceDetailListBean item = new TstoregeInDeviceBean.tstoregeInDeviceDetailListBean();
                            item.setCreateName(createName);
                            item.setCreateTime(CommonUtils.getTime());
                            item.setImei(content);
                            tstoregeInDeviceDetailList.add(item);

                            mIv_progress.setCurrentValue(tstoregeInDeviceDetailList.size());

                            openMusic(true);
                        }

                    }
                    initAdapter();
                } else {
                    ToastUtils.showToast("设备添加完毕无需再扫");
                    openMusic(false);
                }

                // 添加停顿
                try {
                    Thread.sleep(pauseDuration);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // 设置中断状态
                }

            } else {
                openMusic(false);
            }
        }

        @Override
        public void possibleResultPoints(List<ResultPoint> resultPoints) {

        }
    };

    /*
     * 扫描提示音
     * */
    public void openMusic(boolean sign) {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500); // 参数为振动时长（毫秒）
        if (sign) {
            player = MediaPlayer.create(this, R.raw.succeed);
        } else {
            player = MediaPlayer.create(this, R.raw.error);
        }
        player.start();
    }


}